<?php

class Controller extends BaseController
{
    // Was language detected?
    private $_langWasDetected = false;

    public function init()
    {
        $this->authFrom = 'frontend';
        $this->_detectLang();
    }

    /**
     * Small function to detect lang
     *
     * @return void
     */
    private function _detectLang()
    {
        if (!$this->_langWasDetected) {
            Yii::app()->language = $this->getLang();
            $this->_langWasDetected = true;
        }
    }

    /**
     * @param CAction $action
     * @return bool
     */
    public function beforeAction($action)
    {
        session_start();

        $this->_detectLang();
        $arr_accessController = array(
            'account',
            'antifrod',
            'site',
            'auth',
            'article',
            'feedback',
            'download',
            'remove',
            'test',
            'smsdostup',
            'webmoney',
            'error',
            'robokassa',
            'ipn',
            'pdt',
            'upload',
            'news',
            'plimus',
            'linkchecker',
            'servercallback',
            'init',
        );

        /*----ref to cookie----*/
        $request = Yii::app()->request;
        if ($request->getQuery('ref')>0) {
            $cookie = new CHttpCookie('ref', $request->getQuery('ref'));
            $cookie->expire=time()+604800;
            Yii::app()->request->cookies['ref'] = $cookie;
        }


        if ((Yii::app()->user->isGuest) AND (!in_array(Yii::app()->controller->id, $arr_accessController))) {
            $this->redirect('/site/PleaseLogin');
        }
        $arr_delete_cookie = array('download', 'article', 'webmoney', 'robokassa');
        if (!in_array(Yii::app()->controller->id, $arr_delete_cookie) && isset(Yii::app()->request->cookies['buyed_from_dl_page'])) {
            Yii::app()->request->cookies->remove('buyed_from_dl_page');
        }


        return true;
    }

    private function getLang()
    {
        if (!isset($_COOKIE['lang']) && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
                $pattern = '/^(?P<primarytag>[a-zA-Z]{2,8})' .
                    '(?:-(?P<subtag>[a-zA-Z]{2,8}))?(?:(?:;q=)' .
                    '(?P<quantifier>\d\.\d))?$/';
                $splits = array();
                if (preg_match($pattern, $lang, $splits)) {
                    switch ($splits[1]) {
                        case 'ru':
                            $res = 'ru';
                            break;
                        default:
                            $res = 'en';
                    }
                } else {
                    $res = 'ru';
                }
                setcookie('lang', strtolower($res), 0x6FFFFFFF, '/');
                return strtolower($res);
            }
        } else if (isset($_COOKIE['lang'])) {
            switch (strtolower($_COOKIE['lang'])) {
                case 'ru':
                    return 'ru';
                    break;
                case 'en':
                    return 'en';
                    break;
                default:
                    setcookie('lang', 'en', 0x6FFFFFFF, '/');
                    return 'en';
            }
        }

        return 'en';
    }

    public function detectLastUserAuthAndStatistic()
    {
        $user_statistic = new UserStatistic();
        if (!Yii::app()->user->isGuest) {
            $transaction = Yii::app()->db->beginTransaction();
            try {
                if (!isset($_SESSION['user_'])) {
                    $user_model = new User;
                    $user_statistic->setUserStat();
                    $user_model->addLastIpDate();

                    $_SESSION['user_'] = Yii::app()->user->getId();
                }

                if (isset($_SESSION['fp']) && !isset($_SESSION['antifrod_login_actions'])) {
                    $_SESSION['antifrod_login_actions'] = true;
                    /** Antifrod */
                    $frod = new AntifrodBase();
                    $frod->setBuyAuthIP();
                    $frod->setRealAndFakeLocation();
                    $log_data_id = $frod->setAntifrodAuthLog();
                    $frod->checkSuspectLogin($log_data_id);
                    /** -------- */
                }
                $transaction->commit();
            }
            catch (Exception $e)
            {
                Yii::log($e->getMessage(), 'error', 'antifrod');
                $transaction->rollBack();
            }
        }
    }
}
